
import UIKit

//MARK: - Button
extension UIButton {
    // https://www.jianshu.com/p/c78ef14b30e5
    
    /// 图片在右位置
    /// - Parameter spacing: 间距
    func icon(inRight spacing: CGFloat) {
        let size = self.imageView?.frame.size
        
        imageEdgeInsets = UIEdgeInsets(top: 0, left: CGFloat(titleLabel?.intrinsicContentSize.width ?? 0) + spacing / 2, bottom: 0, right: -CGFloat(titleLabel?.intrinsicContentSize.width ?? 0) - spacing / 2)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: -CGFloat(size?.height ?? 0) - spacing / 2, bottom: 0, right: CGFloat(size?.height ?? 0) + spacing / 2)
    }
    
    /// 图片在左位置
    /// - Parameter spacing: 间距
    func icon(inLeft spacing: CGFloat) {
        // 图片在左，文字在右
        imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing / 2, bottom: 0, right: spacing / 2)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing / 2, bottom: 0, right: -spacing / 2)
    }
    
    /// 图片在上面
    /// - Parameter spacing: 间距
    func icon(inTop spacing: CGFloat) {
        
        let img_W = self.imageView?.frame.size.width ?? 0
        let img_H = self.imageView?.frame.size.height ?? 0
        let tit_W = self.titleLabel?.intrinsicContentSize.width ?? 0
        let tit_H = self.titleLabel?.intrinsicContentSize.height ?? 0
        
        imageEdgeInsets = UIEdgeInsets(top: -tit_H - spacing, left: 0, bottom: 0, right: -tit_W)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: -img_W, bottom: -img_H - spacing, right: 0)
    }
    
    /// 图片在 下面
    /// - Parameter spacing: 间距
    func icon(inBottom spacing: CGFloat) {
        let size = self.imageView?.frame.size
        //图片在下，文字在上
        imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -CGFloat(titleLabel?.intrinsicContentSize.height ?? 0) - spacing, right: -CGFloat(titleLabel?.intrinsicContentSize.width ?? 0))
        titleEdgeInsets = UIEdgeInsets(top: -CGFloat(size?.height ?? 0) - spacing, left: -CGFloat(size?.width ?? 0), bottom: 0, right: 0)
    }
}

